package com.ericscode.html5.example.websocket.server;

import java.io.IOException;
import java.io.Serializable;

import net.tootallnate.websocket.WebSocket;
import net.tootallnate.websocket.WebSocketDraft;
import net.tootallnate.websocket.WebSocketServer;

public class WebchatServer extends WebSocketServer implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -2188631488450406650L;

	public WebchatServer(int port) {
		super(port);
	}
	
	@Override
	public void onClientOpen(WebSocket conn) {
		try {
            this.sendToAll(conn + " entered the room!");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        System.out.println(conn + " entered the room!");
	}

	@Override
	public void onClientClose(WebSocket conn) {
		try {
            this.sendToAll(conn + " has left the room!");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        System.out.println(conn + " has left the room!");
	}

	@Override
	public void onClientMessage(WebSocket conn, String message) {
		try {
            this.sendToAll(conn + ": " + message);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        System.out.println(conn + ": " + message);
	}

	
	public static WebchatServer startServer(int port) {
		WebchatServer server = new WebchatServer(port);
		server.start();
		System.out.println("ChatServer started on port: " + server.getPort());
		return server;
	}
	
	public static void stopServer(WebchatServer server) {
		System.out.println("Stopping ChatServer on port: " + server.getPort());
		try {
			server.stop();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
